package com.phpxiu.app.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.adapter.RoomGiftPagerAdapter;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.LiveRoomInfo;
import com.phpxiu.app.model.MsgSender;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.event.OnLvUp;
import com.phpxiu.app.model.event.OnUpdateBalance;
import com.phpxiu.app.model.gift.Gift;
import com.phpxiu.app.model.msg.IMGiftMsg;
import com.phpxiu.app.model.response.GiftModel;
import com.phpxiu.app.model.response.MsgModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.RoomPresenter;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.UserAccount;
import com.phpxiu.app.view.custom.CirclePageIndicator;
import com.phpxiu.app.view.custom.RingProgressView;
import com.phpxiu.app.view.custom.VerticalImageSpan;
import com.tencent.TIMMessage;
import com.tencent.TIMValueCallBack;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;


/**
 * @file
 * @brief  房间赠送礼物，选择礼物面板对话框
 * @author 吴金洲
 * @note 房间赠送礼物，选择礼物并赠送,连击送礼等UI逻辑
 * @see com.phpxiu.app.supports.selector.TimePopupWindow
 *
 */
public class GiftPanel extends Dialog implements View.OnClickListener,RoomGiftPagerAdapter.OnGiftItemSelectedCallBack{
    private final static int HANDLER_REFRESH_COUNT=0x555;
    private final static int HANDLER_CONTINUE_SEND_FINISH=0x556;
    public final static int REFRESH_BALANCE=0x557;
    private final static SpannableStringBuilder BALANCE_BUILDER=new SpannableStringBuilder();
    private final static String BALANCE_END_ICON_STR="icon_str";
    private final static int MAX_COUNT=3000;//最大到计时
    private String BALANCE_START_TXT=null;
    private VerticalImageSpan endImageSpan;
    private ViewPager mGiftPager;
    private RoomGiftPagerAdapter mAdapter;
    private CirclePageIndicator indicator;
    private LinearLayout rechargeBtn;
    protected TextView balanceInfoTv;
    private Button sendGiftBtn;
    private RelativeLayout countSendGiftBtn;//倒计时按钮
    private TextView giftSendCountView;
    private RingProgressView countProView;//到计时进度条
    private Gift currentGift;//当前选中的礼物
    private CountThread countThread=null;
    private Handler childHandler;
    private OKHttpParam sendGiftParam;//赠送礼物参数
    protected long coin;//余额

    private GiftPanelOperaCallBack callBack;
    private LiveRoomInfo roomInfo;
    private MsgSender mMsgSender;
    protected int currentLvl=0;
    protected RoomPresenter roomPresenter;
    private LiveRoomAnimWin liveRoomWin;
    protected Handler handler;
    public GiftPanel(Context context) {
        super(context, R.style.shareBoardDialog);
        handler=new IHandler(this);
        init(context);
    }

    final private void init(Context context){
        setContentView(R.layout.gift_picker_panel);
        findViewById(R.id.gift_panel_bg).setOnClickListener(this);
        coin= MySelfInfo.getInstance().getMoney();
        if(countThread==null) {
            countThread = new CountThread();
            countThread.start();
        }
        mGiftPager=(ViewPager)findViewById(R.id.main_room_window_gift_pager);
        indicator=(CirclePageIndicator)findViewById(R.id.main_room_window_gift_pager_indicator);
        rechargeBtn=(LinearLayout)findViewById(R.id.go_recharge_btn);
        rechargeBtn.setOnClickListener(this);
        balanceInfoTv=(TextView)findViewById(R.id.gift_box_user_account_balance_info);
        endImageSpan=new VerticalImageSpan(getContext(), R.mipmap.diamond_icon);
        formatBalance(coin+"");
        sendGiftBtn=(Button)findViewById(R.id.gift_box_send_gift_btn);
        sendGiftBtn.setEnabled(false);
        sendGiftBtn.setOnClickListener(this);
        countSendGiftBtn=(RelativeLayout)findViewById(R.id.gift_box_count_send_gift_btn);
        countSendGiftBtn.setOnClickListener(this);
        giftSendCountView=(TextView)findViewById(R.id.gift_box_count_view);
        countProView=(RingProgressView)findViewById(R.id.gift_box_count_pro_view);
        countProView.setMax(MAX_COUNT);
        countProView.setProgress(MAX_COUNT);
        countProView.setArcAngle(360);

        mGiftPager.setOffscreenPageLimit(KKYApp.getInstance().GIFTS_PAGES.size());
        mAdapter = new RoomGiftPagerAdapter(getContext(), KKYApp.getInstance().GIFTS_PAGES,this);
        mGiftPager.setAdapter(mAdapter);
        indicator.setViewPager(mGiftPager);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.go_recharge_btn:
                goRecharge();
                break;
            case R.id.gift_box_send_gift_btn:
                onSendGift();
                break;
            case R.id.gift_box_count_send_gift_btn:
                continueGift();
                break;
            case R.id.gift_panel_bg:
                dismiss();
                break;
            default:
                break;
        }
    }

    public void setCallBack(GiftPanelOperaCallBack callBack) {
        this.callBack = callBack;
    }

    /**
     * 当礼物被选中时
     */
    @Override
    public void onGiftItemSelected(Gift gift) {
        if(!gift.isSelected()) {
            KKYUtil.log("选择了礼物:" + gift.getName());
            currentGift=gift;
            sendGiftBtn.setEnabled(true);
        }else{
            KKYUtil.log("没有选择任何礼物");
            currentGift=null;
            sendGiftBtn.setEnabled(false);
        }
    }

    /***
     * 检测发送礼物
     */
    public void onSendGift(){
        KKYUtil.log("发送礼物...");
        if(currentGift==null){
            if(callBack!=null){
                callBack.onSendGiftErrMsg(getContext().getString(R.string.room_gift_not_pick));
            }
            return;
        }
        //连送礼物，则启用连送功能
        if("1".equals(currentGift.getCombo())){
            if(childHandler!=null){
                if(countSendGiftBtn.getVisibility()!=View.VISIBLE){
                    countSendGiftBtn.setVisibility(View.VISIBLE);
                }
                childHandler.removeCallbacksAndMessages(null);
                childHandler.sendEmptyMessage(0);
                sendGiftBtn.setVisibility(View.INVISIBLE);
            }
        }
        sendGiftMsg(currentGift.getId());
    }


    /**
     * 连送礼物
     */
    private void continueGift(){
        KKYUtil.log("连送礼物...");
        if(childHandler!=null){
            childHandler.removeCallbacksAndMessages(null);
            childHandler.sendEmptyMessage(0);
        }
        //执行送礼逻辑
        if(currentGift!=null){
            sendGiftMsg(currentGift.getId());
        }
    }

    /**
     *送礼请求
     */
    private void sendGiftMsg(final String gid){
        if(sendGiftParam==null){
            sendGiftParam=OKHttpParam.builder();
            sendGiftParam.put("tid", CurLiveInfo.getHostID());
            sendGiftParam.put("liveid",roomInfo.getLiveid());
        }
        if(mMsgSender ==null){
            mMsgSender =new MsgSender();
            MySelfInfo.getInstance().getCache(getContext());
            mMsgSender.setUid(MySelfInfo.getInstance().getId());
            mMsgSender.setNickname(MySelfInfo.getInstance().getNickName());
            mMsgSender.setAvatar(MySelfInfo.getInstance().getAvatar());
            mMsgSender.setLvl(MySelfInfo.getInstance().getLvl());
        }
        sendGiftParam.put("gid",gid);
        //校验礼物发送
        OKHttp.post(HttpConfig.API_CHECK_GIFT_SEND, sendGiftParam.jsonParam(), "giftPanel", new OKHttpUIHandler(GiftModel.class) {
            @Override
            public void onSuccess(Object model) {
                try {
                    GiftModel m = (GiftModel) model;
                    KKYUtil.log("送礼验证通过" + m.getResponseStr());
                    if (currentLvl < m.getData().getLvl()) {
                        currentLvl = m.getData().getLvl();//升级
                        if(callBack!=null){
                            callBack.onLevelUp(currentLvl);
                        }
                        MySelfInfo.getInstance().updateCacheInt(getContext(), Constants.USER_LVL, currentLvl);
                        if (mMsgSender != null) {
                            mMsgSender.setLvl(currentLvl);
                        }
                        EventBus.getDefault().post(new OnLvUp(currentLvl));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                MsgModel msgModel = new MsgModel();
                msgModel.setUserAction(Constants.AV_IM_CMD_NOTICE_GIFT);
                IMGiftMsg giftMsg = new IMGiftMsg();
                giftMsg.setFuser(mMsgSender);
                giftMsg.setGiftid(gid);
                updateByGift(gid);
                giftMsg.setTime(System.currentTimeMillis() / 1000);
                msgModel.setActionParam(OKHttp.GSON.toJson(giftMsg));
                if (roomPresenter == null) {
                    return;
                }
                roomPresenter.sendGroupNoticeMessage(OKHttp.GSON.toJson(msgModel), new TIMValueCallBack<TIMMessage>() {
                    @Override
                    public void onError(int i, String s) {
                        if(callBack!=null){
                            callBack.onSendGiftErrMsg("Gift Send Fail by " + i + s);
                        }
                    }

                    @Override
                    public void onSuccess(TIMMessage timMessage) {
                        if(liveRoomWin!=null){
                            liveRoomWin.onReceiveCustomMsg(timMessage, timMessage.getElement(0));//本地显示
                        }
                    }
                });
            }

            @Override
            public void onErr(String errMsg) {
                if(callBack!=null){
                    callBack.onSendGiftErrMsg(errMsg);
                }
            }
        });
    }


    /**
     * 送礼成功更改当余额额
     * @param gid
     */
    private void updateByGift(String gid){
        if(KKYApp.getInstance().GIFTS.size()>0){
            for (Gift g: KKYApp.getInstance().GIFTS){
                if(g.getId().equals(gid)){
                    try {
                        coin=MySelfInfo.getInstance().updateMoney(getContext(), false, Long.parseLong(g.getPrice()));
                        EventBus.getDefault().post(new OnUpdateBalance(coin));//通知各展示余额界面更新余额
                    }catch (NumberFormatException e){
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    }

    /**
     * 更新余额
     * @param event
     */
    @Subscribe
    public void updateBalanceInfo(OnUpdateBalance event){
        Message msg=handler.obtainMessage();
        msg.what=REFRESH_BALANCE;
        msg.obj=event.getCurrentBalance();
        handler.sendMessage(msg);
    }

    /**
     * 前往充值
     */
    private void goRecharge(){
        KKYUtil.log("前往充值...");
        Intent account=new Intent(getContext(),UserAccount.class);
        account.putExtra(UserAccount.EXTRA_PARAM_BALANCE_KEY,coin);
        getContext().startActivity(account);
    }

    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLER_REFRESH_COUNT:
                int pro=(int)msg.obj;
                giftSendCountView.setText((pro/100)+"");
                countProView.setProgress(pro);
                break;
            case HANDLER_CONTINUE_SEND_FINISH:
                countSendGiftBtn.setVisibility(View.INVISIBLE);
                sendGiftBtn.setVisibility(View.VISIBLE);
                break;
            case REFRESH_BALANCE:
                formatBalance(msg.obj.toString());
                break;
            default:
                break;
        }
    }

    public void show(LiveRoomAnimWin roomWin,LiveRoomInfo roomInfo,MsgSender sender,int level,RoomPresenter presenter) {
        liveRoomWin=roomWin;
        this.roomInfo=roomInfo;
        mMsgSender=sender;
        currentLvl=level;
        roomPresenter=presenter;
        super.show();
    }

    @Override
    public void dismiss() {
        if(callBack!=null){
            callBack.onGiftPanelHide();
        }
        super.dismiss();
    }

    private void formatBalance(String balance){
        if(BALANCE_START_TXT==null){
            BALANCE_START_TXT=getContext().getString(R.string.ui_gift_recharge_title);
        }
        BALANCE_BUILDER.clear();
        BALANCE_BUILDER.append(BALANCE_START_TXT).append(balance).append(BALANCE_END_ICON_STR);
        //BALANCE_BUILDER.setSpan(VALUE_COLOR_SPAN, BALANCE_START_TXT.length(), BALANCE_START_TXT.length() + balance.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        BALANCE_BUILDER.setSpan(endImageSpan, BALANCE_START_TXT.length() + balance.length(), BALANCE_START_TXT.length() + balance.length() + BALANCE_END_ICON_STR.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        balanceInfoTv.setText(BALANCE_BUILDER);
    }

    /**
     * 销毁
     */
    public void destroy(){
        if(isShowing()){
            dismiss();
        }
        EventBus.getDefault().unregister(this);
        callBack=null;
        roomInfo=null;
        mMsgSender=null;
        currentLvl=0;
        roomPresenter=null;
        liveRoomWin=null;
        if(countThread!=null){
            countThread.stopLoop();
        }
        if(mAdapter!=null) {
            mAdapter.clearAdapter();
        }
        if(childHandler!=null){
            childHandler.removeCallbacksAndMessages(null);
            childHandler=null;
        }
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
        }
    }

    static class IHandler extends Handler {
        private WeakReference<GiftPanel> win;

        IHandler(GiftPanel win) {
            this.win = new WeakReference<GiftPanel>(win);
        }
        @Override
        public void handleMessage(Message msg) {
            win.get().handleMsg(msg);
        }
    }

    class CountThread extends Thread{
        private int count=-2;
        private Looper mLooper;
        private Timer finishContinueTimer=new Timer(true);
        private TimerTask finishContinueCountDownTask;
        @Override
        public void run() {
            super.run();
            KKYUtil.log("启动了线程："+getName());
            finishContinueCountDownTask=new TimerTask() {
                @Override
                public void run() {
                    if(childHandler!=null){
                        childHandler.sendEmptyMessage(1);
                    }
                }
            };
            finishContinueTimer.schedule(finishContinueCountDownTask,0,100);
            Looper.prepare();
            mLooper=Looper.myLooper();
            childHandler=new Handler(mLooper){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what){
                        case 0://重置
                            childHandler.removeCallbacksAndMessages(null);
                            count=MAX_COUNT;
                            break;
                        case 1:
                            if(count>0){
                                count=count-100;
                                Message m=handler.obtainMessage();
                                m.what=HANDLER_REFRESH_COUNT;
                                m.obj=count;
                                handler.sendMessage(m);
                            }else if(count==0){
                                handler.sendEmptyMessage(HANDLER_CONTINUE_SEND_FINISH);
                                count=-1;
                            }
                            break;
                        default:
                            break;
                    }
                }
            };
            Looper.loop();
        }

        public void stopLoop(){
            if(finishContinueTimer!=null){
                finishContinueTimer.cancel();
                finishContinueTimer=null;
            }
            if(finishContinueCountDownTask!=null){
                finishContinueCountDownTask.cancel();
                finishContinueCountDownTask=null;
            }
            if(childHandler!=null){
                childHandler.removeCallbacksAndMessages(null);
            }
            if(mLooper!=null){
                mLooper.quit();
            }
        }
    }

    public interface GiftPanelOperaCallBack{
        void onGiftPanelHide();
        void onSendGiftErrMsg(String msg);
        void onLevelUp(int newLevel);//升级
    }
}
